/**
 * 
 */
package com.baijia.tianxiao.connect.interceptor;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import com.alibaba.fastjson.JSON;
import com.baijia.tianxiao.connect.common.util.ConnectUtil;
import com.baijia.tianxiao.connect.common.util.InnerAuthToken;
import com.baijia.tianxiao.connect.config.Constants;
import com.baijia.tianxiao.connect.util.TianxiaoInnerConnectUtil;;

/**
 * @author leiruiqi
 *
 */
public class TianxiaoInnerWebSocketHandshakeInterceptor extends HttpSessionHandshakeInterceptor{

	
	private static Logger logger = LoggerFactory.getLogger(TianxiaoInnerWebSocketHandshakeInterceptor.class);
	
	//@Resource
	//private TianxiaoConnectUtil tianxiaoConnectUtil;
	
	private boolean initPort = false;
	
	public void afterHandshake(ServerHttpRequest arg0, ServerHttpResponse arg1, WebSocketHandler arg2, Exception arg3) {
		// TODO Auto-generated method stub
		
	}

	public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
			Map<String, Object> attributes) throws Exception {
		if (request instanceof ServletServerHttpRequest) {  
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
           
            String userToken = (String)servletRequest.getServletRequest().getParameter("user_token");
            
            
            InnerAuthToken innerAuthToken = checkTokenAndGetParams(userToken);
        	
        	if(innerAuthToken == null){
        		return false;
        	}
        	String domain = innerAuthToken.getDomain();
            String bizType = innerAuthToken.getUserType();
        	Long time = innerAuthToken.getTime();
        	
        	
        	
        	//使用userName区分WebSocketHandler，以便定向发送消息  
			if (checkType(bizType)  && checkDomain(domain) && checkExpire(time) ) {
				String websocket_username = TianxiaoInnerConnectUtil.createTxSessionKey(domain, bizType);
				if (StringUtils.isBlank(websocket_username)) {
					return false;
				}

				attributes.put(Constants.SESSION_USERNAME, websocket_username);

				return true;
			}
        }  
		return false;
		
	}
	
	private InnerAuthToken checkTokenAndGetParams(String token){
		InnerAuthToken authToken = null;
		try {
			String jsonStr = ConnectUtil.getBizNameByToken(token);
			authToken =  JSON.parseObject(jsonStr, InnerAuthToken.class);
		} catch (Exception e) {
			logger.error("checkToken error",e);
			return null;
		}
		return authToken;
	}
	
	private boolean checkType(String userType){
		if(StringUtils.isNoneBlank(userType)){
			return true;
		}
		return false;
	}
	private boolean checkDomain(String domain){
		
		if(StringUtils.equals(domain, "inner")){
			return true;
		}
		return false;
	}
	
	private boolean checkExpire(Long tokenTime){
		if(tokenTime != null){
			long time = System.currentTimeMillis()-tokenTime;
			//10分钟过期
			if(time>600000){
				return false;
			}
		}
		
		return true;
	}

	public static void main(String[] args)  {
		 
		String tokenStr="";
		try {
			InnerAuthToken authToken = new InnerAuthToken();
			authToken.setDomain("inner");
			authToken.setUserType("tx-cr");
			authToken.setTime(System.currentTimeMillis());
			
			
			tokenStr = ConnectUtil.getTokenByBizName(JSON.toJSONString(authToken));
			System.out.println(tokenStr);
			
			String jsonString = ConnectUtil.getBizNameByToken(tokenStr);
			
			System.out.println(jsonString);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
}
